﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Scm.Orm.Helper
{
    public class ObjectHandler
    {

        /// <summary>
        /// 对象转字典
        /// </summary>
        /// <param name="Obj"></param>
        /// <returns></returns>
        public static Dictionary<string, String> ObjectToDic<T>(T? Obj)
        {
            Dictionary<string, String> _dic = new();
            if (Obj == null) return _dic;
            Type Type = Obj.GetType();
            PropertyInfo[] PropertyInfos = Type.GetProperties();
            foreach (var Item in PropertyInfos)
            {
                string Name = Item.Name;
                object? Value = Item?.GetValue(Obj);
                if (Value == null) continue;
                _dic?.Add(Name, Value?.ToString()?? "");
            }
            return _dic;
        }


        /// <summary>
        /// 使用 Json 序列化实现 对象的复制
        /// 对于性能有高度要求的场景不建议使用此方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Target"></param>
        /// <param name="Source"></param>
        /// <returns></returns>
        public static T Copy<T>(T Target, object Source)
        {
            var Json = JsonConvert.SerializeObject(Source);
            Target = JsonConvert.DeserializeObject<T>(Json);
            return Target;
        }
    }
}
